﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using DotNetNuke.Framework;
using DotNetNuke.Entities.Users;
using System.Xml;
using DotNetNuke.Web;
using DotNetNuke.Web.Api;
using DotNetNuke.Modules.Dashboard.Components;

using System.Net;
using System.Net.Http;
using System.Web.Http;


namespace DnnDash.SimpleDashboard.Services
{
    public class DashController : DnnApiController
    {
        [HttpGet]
        [AllowAnonymous]
        public string Ping()
        {
            return "Dnn Dash Version 01.00.00";
        }

        [HttpGet]
        [DnnAuthorize(StaticRoles="Administrators")]
        public string PingAdmin()
        {
            return "Dnn Dash Version (Admin) 01.00.00";
        }

        [HttpGet]
        [RequireHost]
        public string PingHost()
        {
            return "Dnn Dash Version (Host) 01.00.00";
        }


        [HttpGet]
        [AllowAnonymous]
        public HelloWorldInfo HelloWorld()
        {
            HelloWorldInfo result = new HelloWorldInfo();
            result.Username = this.UserInfo.Username;
            result.portalId = this.PortalSettings.PortalId;
            result.Message = "Hello, Webinar Attendees!";
            return result;
        }

        /// <summary>
        /// Returns DotNetNuke dashboard controls
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public XmlElement Controls()
        {
            
            string result = "<dashboard>";
            List<DashboardControl> dashControls = DashboardController.GetDashboardControls(true);
            if (dashControls != null && dashControls.Count > 0)
            {
                string dashXml = @"<dashControl name=""{0}"">{1}</dashControl>";
                foreach (DashboardControl dashboard in dashControls)
                {
                    StringWriter sw = new StringWriter();
                    XmlTextWriter xw = new XmlTextWriter(sw);
                
                    var controller = Activator.CreateInstance(Reflection.CreateType(dashboard.ControllerClass)) as IDashboardData;
                    if (controller != null)
                    {
                        controller.ExportData(xw);
                        result += string.Format(dashXml, dashboard.LocalizedTitle, sw.ToString());
                    }
                }
                
            }
            result += "</dashboard>";
            //return result;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);
            XmlElement el = (XmlElement)doc.SelectSingleNode("dashboard");
            return el;
        }
        /// <summary>
        /// This method allows the get/post of the name of a Dnn Dashboard control.  It is used
        /// to synchronise a favorite dashboard control to view as the default.  By exposing as a 
        /// service, it is available to all devices/apps using this service endpoint
        /// </summary>
        /// <param name="nameJson">optional string parameter for POST requests</param>
        /// <returns></returns>
        [RequireHost]
        [HttpGet, HttpPost]
        public object FavoriteDashControl()
        {
            return FavoriteDashControl(null);
        }
        [RequireHost]
        [HttpGet,HttpPost]
        public object FavoriteDashControl(string nameJson)
        {
            SimpleResult result = new SimpleResult("Invalid Result");
            try
            {

                UserInfo user = this.UserInfo;
                const string userKeyFormat = "dashControlName_User{0}";
                if (user != null)
                {
                    HttpRequestMessage req = Request;
                    System.Web.HttpRequest rawRequest = System.Web.HttpContext.Current.Request;
                    //get the key used to store the favorite dashboard control name
                    string userKey = string.Format(userKeyFormat, user.UserID);
                    if (rawRequest.RequestType == "POST")
                    {
                        //called as POST
                        if (nameJson == null)
                        {
                            //read in input
                            //NOTE: With WebAPI, you can now read in Asynchronously
                            //using the HttpRequestMessage object
                            rawRequest.InputStream.Position = 0;
                            nameJson = new StreamReader(rawRequest.InputStream).ReadToEnd();
                        }
                        //translate request from string json to object
                        SimpleRequest request = JsonSerializer.Deserialize<SimpleRequest>(nameJson);
                        //store data in Host settings
                        string controlName = (string)request.data;
                        DotNetNuke.Entities.Controllers.HostController.Instance.Update(userKey, controlName);
                        result.Result = "success";
                        result.data = null;
                    }
                    else
                    {
                        if (rawRequest.RequestType == "GET")
                        {
                            //called as GET

                            string controlName = DotNetNuke.Entities.Controllers.HostController.Instance.GetString(userKey, null);
                            if (string.IsNullOrEmpty(controlName))
                                controlName = "null";

                            //set values for return 
                            result = new SimpleResult("success");
                            result.data = controlName;

                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if (DEBUG)
                result = new DebugResult("error", true, ex);
#else
                result = new FullResult("error", ex);
#endif
            }
            return result;
        }
    }
    public class HelloWorldInfo
    {
        public string Username {get;set;}
        public int portalId { get; set; }
        public string Message {get;set;}
    }
}
